
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
var request = require('request')
const db = cloud.database()
const sendMessage = async(e,openid,pid) => {
  try {
    const result = await cloud.openapi.subscribeMessage.send({
      touser: openid , //要推送给那个用户
      page: 'pages/order/order', //要跳转到那个小程序页面
      data: {//推送的内容
        thing9:{
           value: e.slotId +'号充电桩'
       },
        thing4: {
          value:  e.stubDisplay
        },
        phrase10: {
          value: '充电已结束'
        }, 
        thing8: {
          value: e.reason?e.reason:'状态异常'
        }
      },
      templateId: 'ejT7D2ryZ2w-DEYOdZSa2fnMN-KqGjpIsrPzewMfWTk' //模板id
    })
    console.log(result)
    db.collection('p_pushlist').doc(pid).remove()
    return result
  } catch (err) {
    console.log(err)
    return err
  } 
}
exports.main = async(event, context) => {
 let userList = (await db.collection('p_pushlist').get()).data
 console.log(userList)
 userList.forEach(item =>{
  let rq = new Promise((resolve, reject) => {
    request.post('http://47.104.75.15/campus/api/power/orders?os=' + item.os + '&userId=' + item.userId + '&token=' +item.token,
     (error, response, body) => {
      if (error) {
        reject()
      } else {
        try {
          resolve(body)
          let bkdata = JSON.parse(body)
          if(bkdata.data[0].status == 1){
            sendMessage(bkdata.data[0],item._openid,item._id)
          }else{
          
         }
        } catch (e) {
          reject()
        }
      }
    })
  })
 })
  var os = 'android'
  var userId = '104657'
  var token = '3130343635377C616E64726F69647C30'
 
  return 0
}